Skip to content

feat: universal Java/Android input support and JDK JImage - #31

Merged
VillanCh merged 22 commits into
mainfrom
feat/universal-input-formats
Nov 13, 2026
Merged

VillanCh merged 22 commits into
mainfrom
feat/universal-input-formats

Conversation

@VillanCh

@VillanCh VillanCh commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Make input handling structure-aware, add native JDK JImage support (including
compact-cp and big-endian images), contain malformed inputs, and add layered
DEX recovery with traceable method stubs and class shells.

Universal input classification

  • New internal/inputkind: classify by content magic, then archive structure, then filename extension.
  • Renamed APK/APKS/JMOD/AAR/JImage files reach the correct pipeline.
  • CLI decompile, dex2jar, jimage2jar, and inspect share the classifier.

Java archives

  • .jmod: strip the 4-byte JM\x01\x00 prefix (top-level and nested).
  • .aar: classes.jar and libs/*.jar are decompiled.
  • .par: accepted as an archive.
  • Flat export now resolves nested JARs (WAR/WEB-INF/lib, EAR/lib, AAR, fat JARs) instead of warning and skipping them.
  • Class-level containment: a malformed or future-version class becomes a bounded, single-line fallback .java entry while the remaining archive continues. Historical // decompile parse failed and // decompile dump failed markers are preserved.
  • Structured ArchiveEntryReport now reports complete, partial, or fallback, plus stub methods and diagnostics. Resource and cancellation failures still abort the request.

Android containers

  • .apks / .xapk / .apkm / .apkx: walk nested APKs, prefer universal.apk, select one standalone variant, skip resource-only splits, dedupe identical classes, and fail on conflicting definitions.
  • .aab: translate every <module>/dex/classes*.dex.
  • Default nested-APK bound is 512; a real bundletool split bundle with 181 nested APKs translates correctly.

Adversarial Java ecosystem hardening

  • Bound tiny-input JImage amplification: resource counts, every decompressor layer, and running compact-cp reconstruction are checked before allocation/append.
  • Reject malformed ZIP AES extras without panic, verify CRC even when the stored CRC is zero, and reject lowercase Windows drive paths.
  • Flat and structured archive export now share context, parser/work budgets, byte/entry/output limits, and multi-release target selection. Flat per-entry path/read/write failures no longer report false success.
  • Validate classfile minor/preview policy, Code length, and all constant-pool links including unused version-gated constants before entering source recovery.
  • Keep minimal DEX interface and annotation shells verifier-safe even when original access flags contain unsupported bits; preserve parameter annotations when representable.
  • Restore DEX annotation-interface defaults and verify them through JVM reflection.
  • Bound recovery diagnostics by field, record count, and total JSON payload with deterministic diagnostics.truncated evidence.
  • Add focused fuzz seeds for JImage, ZIP, bounded class decompilation, and full DEX recover mode.

Failure containment and layered DEX recovery

  • Harden DEX payload decoding and analysis-state allocation before indexing or allocating amplified state.
  • Keep strict APIs transactional and unchanged. --stub-methods-only only stubs recognized method-local capability gaps.
  • --best-effort adds layered recovery: normal translation, method stubs, a fresh declaration-preserving class shell, a reduced-metadata shell, then a minimal identity shell.
  • One malformed class no longer blocks good classes in the same DEX/APK/AAB after container parsing and whole-file validation succeed.
  • Unsupported static values fail closed: representable ConstantValue data is preserved; otherwise recovery replaces or synthesizes a throwing <clinit> instead of exposing silent null/zero defaults.
  • If a superclass/interface becomes minimal, dependent classes recursively become declaration shells, including when the dependent appeared earlier in the input.
  • Recovery evidence is deterministic and travels with the output: DetailedReport, META-INF/javajive/diagnostics.json, a bounded JavaJiveRecovery class attribute, and leading // javajive recovery: decompiler comments.
  • Add typed failure kind/scope/stage/action/severity fields, class/method/drop counters, JVM annotation long/float/double values, and explicit classfile count/length bounds.
  • Malformed containers, whole-file validation failures, unsupported DEX versions/sections, duplicate class identities, resource limits, and internal/output failures still abort without a JAR.

JDK JImage

  • Native jimage package: 28-byte header, redirect/offset tables, attribute streams, string table, and on-demand resource reads.
  • Supports uncompressed, zlib (zip), and compact-cp (constant-pool string sharing) resources, plus big-endian images.
  • compact-cp reconstruction is byte-identical to the plain image, verified with jlink --compress=1.
  • JImageToJar / OpenJImageFile facade and jimage2jar CLI.
  • decompile converts JImage to a package-layout JAR view and reuses flat/structured export; inspect reports jimage with per-resource hashes and compression state.

Tests

  • testdata/external with real Tomcat WARs, bundletool APK/AAB/APKS (universal and a 181-APK split bundle), an AndroidX AAR, Androguard/Apktool/dex2jar fixtures, and synthetic XAPK/APKM/EAR containers.
  • Tests classify, inspect, decompile, and translate every sample; malformed truncations assert no panics.
  • Pure-Go compact-cp unit tests plus opt-in jlink --compress=1 and --endian big integration tests.
  • Fuzz seed corpora for the classifier, JImage/compact-cp readers, inspect, Android containers, and full DexToJar/best-effort conversion.
  • Real external corpus and JDK/JLink integration tests are explicit opt-in (JAVAJIVE_EXTERNAL_EVAL=1, JAVAJIVE_JIMAGE_INTEGRATION=1). Required PR CI keeps small synthetic container regressions, archive containment, DEX policy, and no-panic tests.

Verification

  • go build ./... and go vet on changed packages.
  • Focused tests pass: ./dex2jar/..., ./classparser/jarwar, ./classparser -run '^(TestArchiveClass|TestClassFallbackText|TestT22T23SharedWorkBudgetPipeline)$', ./cmd/javajive, root facade, ./jimage, and default ./test/external.
  • JAVAJIVE_EXTERNAL_EVAL=1 go test ./test/external passes.
  • JAVAJIVE_JIMAGE_INTEGRATION=1 go test ./jimage ./test/external passes.
  • Real JDK 21 lib/modules: 30,957 entries / 28,060 classes / complete.
  • jlink --compress=1 (compact-cp): 7,957 entries / 7,507 classes / complete; reconstructed Object.class is byte-identical.
  • jlink --endian big: reconstructed Object.class is byte-identical.
  • bundletool-splits.apks: 181 nested APKs, 4 DEX / 1,298 classes.
  • jimage2jar real JDK image: 138 MB JAR in ~0.3s.

Known boundary

  • DEX remains a bounded vertical slice. Recovery preserves discoverability and declarations but partial output is not a claim of semantic equivalence.
  • Full JDK image decompilation is large (~28k classes); use inspect or jimage2jar first.
  • The full classparser suite is CI-sharded; local targeted tests were used. The unrelated TestT22OutputBytesLpm1LeafBranchBushyRewrite failure reproduces unchanged on baseline HEAD, so it is not introduced by this PR.

- classify inputs by magic, archive structure, then extension
- support JMOD (header strip), AAR/PAR, and nested JAR flat export
- support APKS/XAPK/APKM/AAB with universal/split selection and dedupe
- add native jimage reader (header/index/attributes/strings/zlib/ZIP view)
- route decompile/dex2jar/jimage2jar/inspect by detected container
- add JImageToJar/OpenJImageFile facade and jimage2jar CLI
- update docs and tests
- implement compact-cp constant-pool reconstruction and big-endian JImage support
- raise the default nested-APK bound to 512 for real split bundles
- add testdata/external real samples, synthetic XAPK/APKM/EAR, and malformed truncation tests
- add fuzz seed corpora for classifier, JImage/compact-cp, inspect, and Android containers
- add container/JImage/external tests to CI
- Harden DEX switch/fill-array payload decoding against negative, wrapped,
  truncated, and final-word targets; reject instruction×register state
  amplification before allocation.
- Add explicit strict/best-effort DEX conversion APIs and --best-effort for
  dex2jar and Android decompile. Recognized method-local capability gaps become
  verifier-safe UnsupportedOperationException stubs with per-method diagnostics;
  malformed input, unsupported versions, resource limits, and internal errors
  still abort without a JAR.
- Isolate Java archive class failures: malformed and future-version classes
  become bounded one-line fallback sources while other entries continue.
  Structured archive reports distinguish complete, partial, and fallback
  outcomes and carry stub/diagnostic evidence.
- Keep historical parse/dump failure markers to avoid downstream regressions.
- Move real external-corpus and JDK/JLink integration tests behind explicit
  environment gates and keep required PR CI on small synthetic and focused
  containment regressions.
- Remove the unused hasDEXMagic helper so the coverage contract does not
  carry a dead 0%-covered function.
- Cover container predicates, input-magic branches, unknown policies, missing
  files, and empty/malformed APK/APKS/AAB inputs.
- Cover the full CapabilityError contract, restoring dex2jar/report to 100%.
- Keep the measured DEX coverage ratios above the existing baseline.
Cache loop bodies and exits across an analysis-only rewrite window instead of rebuilding every loop body for every container node. LoopJmpRewriter reuses the scan's answers when its pre-rewrites changed nothing, and protected retry regions keep the cache disabled. A 7 KB/60-loop class drops from 7.78 s, 4.79 GB and 38.6M allocations to 1.70 s, 635 MB and 3.55M allocations.

Index statement dominance with parent links, borrow the cached IDom analysis without a deep copy, and rebuild successor lists with flat generation stamps instead of one map per source node.

Restore shielded Java literals and comments with one linear marker pass and hoist the throw-cast regexes; the FMParser profile attributed 445 MB of copying to the per-span ReplaceAll loop. Read the runtime g register on arm64 so ambient JDEC lookups no longer format a goroutine stack.
Validate only the requested inventory group in -run jobs, memoize go test -list per package, and list packages with bounded parallelism. The full contract check still seals every row.

Precompile race/coverage suites with two workers and run independent package test binaries two at a time, while preserving selectors, five-minute per-binary timeouts, clean environments, per-suite event verification, fail-closed dispatch, and the coverage baseline check.

Warm-cache required gates: algorithm 78 s to 27 s, DEX 81 s to 24 s, corpus 44 s to 15 s, full inventory check 26 s to 9 s.
Run up to four independent package test binaries concurrently, capped by GOMAXPROCS. Compile the external-APK inspect suite twice so its race check and coverage check run concurrently instead of paying both instrumentation costs in one process; coverage remains 4844/5727 statements and both runs must pass the full sealed selector.

Remove per-case Frame.Clone, NewFrame, and locals allocations from the exhaustive 797k-case stack-diagram test while snapshotting the caller-owned locals and stack to keep the immutability assertion. Allocation drops from ~2.4 GB to ~0.6 GB.

Warm-cache required gates are now ~17-18 s for algorithm, ~17 s for DEX, ~13-15 s for corpus, and ~9 s for the full inventory check.
Replace per-target switch-case rescans with one-pass per-target jump-only predicates. The loop-exit inline-case check and the empty-case merge search previously rebuilt the whole ordered case map once per candidate target, making a large lexer switch O(cases^2).

Stop the per-load reaching-store repair BFS at the current definition or a second distinct definition, and reuse a generation-stamped visited map plus queue across queries. Reuse the loop-analysis scratch for methods whose protected retry boundaries keep the body memo disabled.

FMParserTokenManager drops from 24.8 s / 21.9 GB / 45.2M allocations to 7.9 s / 3.65 GB / 17.7M. Add differential tests comparing the one-pass switch predicate with the per-target query and the early-exit reaching query with the map-returning oracle; required corpus and race algorithm gates pass.
Split loop bodies into a topology-only base set and the protected-retry augmentation. Cache the base across rewrite steps and invalidate only loops whose dominator subtree or immediate adjacency changed; added/removed nodes and irreducible CFGs invalidate conservatively. Bodies without protected retry boundaries share the base set, while protected bodies clone before augmenting so every ProtectedEnd side effect remains.

Answer the per-load reaching-store repair from the sparse reaching facts when the SemanticCFG knows the opcode, falling back to the structural walk otherwise, and charge BFS visits to CounterGraphScans in batches.

Reuse the mutable analysis graph, edge storage, successor tables and dominance index across topology epochs. commonLoopExit reuses generation-stamped distances/queues, exclusive-terminal tests take a cached node-live predicate, and protected-body augmentation no longer allocates Set.List snapshots.

FMParserTokenManager drops from 24.8 s / 21.9 GB / 45.2M allocations to 4.8 s / 1.79 GB / 14.2M (5.2x/12.2x/3.2x). Add localized loop-base invalidation coverage and a differential test comparing the dataflow reaching query with the structural walk.
Keep the branch's pure-Go required CI workflow while retaining main's scheduler scope helpers and cache-ignore cleanup. Resolve the CI contract tests to the branch workflow.
Inventory and run every Fuzz* seed corpus in required CI, including classparser, decoder audit, DEX-to-JAR, DEX input, inspect, inputkind, ZIP and JImage. Seed corpora run under the existing race/coverage gates.

Add concurrent class decompilation under the race detector, pre-canceled and mid-flight cancellation checks that publish no source, and cross-process fingerprint comparison to catch process-local map-hash order dependence.

Sealed inventory updated; contract, corpus, algorithm and DEX gates pass.
- reuse the statement dominator tree map and child slices across topology
  epochs instead of rebuilding them after every rewrite step
- replace the loop-exit BFS whole-graph visited map with index-based scratch
  traversal over the existing reverse adjacency
- share reaching-definition sets when one side is a subset, avoiding identical
  rebuilt slices at joins
- memoize switch jump-only targets; switch tables are analyzer-owned and never
  rewritten, so the exit search no longer re-derives them per body node
- replace per-name \bname\b regexp compiles with an exact literal word scanner
  (randomized equivalence test against Go regexp) in the dumper and rewriter
- clone protected loop bodies under one read lock and hoist constant regexes
@VillanCh
VillanCh merged commit 5b4f0ce into main Nov 13, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant